package com.example.restaurant.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.restaurant.common.CommonsUtil;
import com.example.restaurant.common.Log;
import com.example.restaurant.common.RestaurantException;
import com.example.restaurant.common.allenum.MerchantStatus;
import com.example.restaurant.controller.form.AddPersonForm;
import com.example.restaurant.controller.form.AddUserForm;
import com.example.restaurant.controller.form.PutStorePersonNameForm;
import com.example.restaurant.dao.StoreMapper;
import com.example.restaurant.dao.UserStoreMapper;
import com.example.restaurant.model.Store;
import com.example.restaurant.model.User;
import com.example.restaurant.dao.UserMapper;
import com.example.restaurant.model.UserStore;
import com.example.restaurant.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.restaurant.service.dto.FeiDishDto;
import com.example.restaurant.service.dto.GetStoreNameDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author x
 * @since 2022-09-29
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private StoreMapper storeMapper;

    @Resource
    private UserStoreMapper userStoreMapper;

    @Override
    public boolean checkUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        List<User> users = userMapper.selectList(queryWrapper);
        if(users.size()>0){
            throw new RestaurantException("该账号已被占用，请修改");
        }else {
            return true;
        }
    }

    @Override
    @Transactional
    public boolean addUser(AddUserForm addUserForm) {
        String password = addUserForm.getPassword();
        String md5 = CommonsUtil.md5(password);
        User user = BeanUtil.copyProperties(addUserForm, User.class);
        user.setPassword(md5);
        user.setRegisterTime(new Date());
        user.setRoleId(1);
        user.setStatus(MerchantStatus.START.getCode());
        //验证重复
        String username = user.getUsername();
        boolean b = checkUsername(username);
        if(b){
            int result = userMapper.insert(user);
            if(result>0){
                return true;
            }else{
                throw new RestaurantException("注册失败");
            }
        }else{
            throw new RestaurantException("账号已被占用,请重新输入");
        }
    }

    @Override
    public User doLogin(String username, String password) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        String md5 = CommonsUtil.md5(password);
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",md5);
        User user = userMapper.selectOne(queryWrapper);
        if(user!=null){
            return user;
        }else {
            throw new RestaurantException("登录失败，请重试");
        }
    }


    @Override
    public List<User> getPerson(int userId, String username) {
        //通过userId查询所有门店Id
        List<Store> stores = storeMapper.getStore(userId);
        if(stores.size()!=0){
            List<Integer> list = new ArrayList<>();
            for (Store s: stores
            ) {
                //通过门店ID查询所有的用户id
                QueryWrapper<UserStore> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("store_id",s.getId());
                UserStore userStores = userStoreMapper.selectOne(queryWrapper);
                if(userStores.getUserId()!=userId){
                    list.add(userStores.getUserId());
                }
            }
            if(list.size()!=0){
                //通过用户Id查询用户信息
                List<User> users = new ArrayList<>();
                for (int i:
                        list) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    queryWrapper.like("username",username);
                    queryWrapper.eq("id",i);
                    User user = userMapper.selectOne(queryWrapper);
                    if(user!=null){
                        users.add(user);
                    }
                }
                if(users.size()!=0){
                    return users;
                }else{
                    throw new RestaurantException("您还没有员工");
                }
            }else {
                throw new RestaurantException("您还没有员工");
            }
        }else{
            throw new RestaurantException("您还没有门店");
        }
    }

    @Override
    //根据门店id和店长名查询
    public IPage<GetStoreNameDto> getStoreName(int storeId, String username,int current,int size) {
        if(storeId<1){
            throw new RestaurantException("请选择门店");
        }
        Page<GetStoreNameDto> getStoreNameDtoPage = new Page<>(current, size);
        String username1 = "%" + username + "%";
        IPage<GetStoreNameDto> storeName = userMapper.getStoreName(getStoreNameDtoPage, storeId, username1);
        if(storeName.getTotal()==0){
            throw new RestaurantException("您还没有店长");
        }
        return storeName;
    }



    @Override
    @Transactional
    public boolean addPerson(AddPersonForm addPersonForm) {
        String password = addPersonForm.getPassword();
        String md5 = CommonsUtil.md5(password);
        User user = BeanUtil.copyProperties(addPersonForm, User.class);
        user.setPassword(md5);
        user.setRegisterTime(new Date());
        user.setStatus(MerchantStatus.START.getCode());
        user.setRoleId(2);
        //验证重复
        String username = user.getUsername();
        boolean b = checkUsername(username);
        if(b){
            int result = userMapper.insert(user);

            Integer id = user.getId();
            int storeId = addPersonForm.getStoreId();
            UserStore userStore = new UserStore();
            userStore.setUserId(id);
            userStore.setStoreId(storeId);
            int insert = userStoreMapper.insert(userStore);
            if(result>0&&insert>0){
                return true;
            }else{
                throw new RestaurantException("注册失败");
            }
        }else{
            throw new RestaurantException("账号已被占用,请重新输入");
        }
    }

    @Override
    @Transactional
    @Log
    public boolean putStorePersonName(PutStorePersonNameForm putStorePersonNameForm) {
        log.info("{}",putStorePersonNameForm);
       String password = putStorePersonNameForm.getPassword();
       log.info("{}",password);
        String md5 = CommonsUtil.md5(password);

        User user = BeanUtil.copyProperties(putStorePersonNameForm, User.class);
        user.setPassword(md5);
        user.setRoleId(2);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",putStorePersonNameForm.getId());
        int update = userMapper.update(user, queryWrapper);
        if(update<1){
            throw new RestaurantException("修改失败");
        }
        return true;
    }

    @Override
    @Transactional
    @Log
    public boolean delPersonById(int id) {
        int i = userMapper.deleteById(id);
        if(i<1){
            throw new RestaurantException("删除失败");
        }
        QueryWrapper<UserStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        int delete = userStoreMapper.delete(queryWrapper);
        if(delete<1){
            throw new RestaurantException("这个店长没有关联的门店");
        }
        return true;
    }
}
